#!usr/bin/env python
# *- coding:utf-8 -*-
# Andy Create @ 10/18/2019 11:03 AM
import re

from multiselectfield.forms.fields import MultiSelectFormField
from django import forms
from django.core.validators import ValidationError

from sales import models


def password_validator(password):
    # password contains lower, upper, digit
    if any(char.isdigit() for char in password) and any(
            char.islower() for char in password) and any(char.isupper() for char in password):
        return password
    else:
        raise ValidationError('8-15位大小字母及数字')


class Register_form(forms.Form):
    username = forms.CharField(required=True, max_length=16, error_messages={'required': '用户名必填', },
                               widget=forms.TextInput(attrs={'placeholder': '请输入用户名', 'class': 'username',
                                                             'autocomplete': 'off', }))
    password = forms.CharField(required=True, max_length=32, error_messages={'required': '密码必填'},
                               widget=forms.PasswordInput(attrs={'placeholder': '请输入密码',
                                                                 'class': 'password',
                                                                 'oncontextmenu': 'return false',
                                                                 'onpaste': 'return false'}),
                               validators=[password_validator])
    re_password = forms.CharField(required=True, max_length=32, error_messages={'required': '密码必填'},
                                  widget=forms.PasswordInput(
                                      attrs={'placeholder': '再次输入密码', 'class': 'confirm_password',
                                             'oncontextmenu': 'return false', 'onpaste': 'return false'}),
                                  validators=[password_validator])
    telephone = forms.CharField(required=True, max_length=11, error_messages={'required': '电话必填'},
                                widget=forms.TextInput(
                                    attrs={'placeholder': '请输入电话号码', 'class': 'phone_number', 'autocomplete': 'off'}))
    email = forms.EmailField(required=True, error_messages={'required': '邮箱必填'},
                             widget=forms.EmailInput(attrs={'placeholder': '请输入邮箱', 'class': 'email',
                                                            'oncontextmenu': 'return false',
                                                            'onpaste': 'return false'}))

    def clean_username(self):
        username = self.cleaned_data['username']
        username_exists = models.UserInfo.objects.filter(username=username).exists()
        if username_exists:
            raise ValidationError('用户名已存在')
            # self.add_error('username', '用户名已存在')
        else:
            return username

    def clean_email(self):
        pattern = re.compile(r'^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+.[a-zA-Z0-9_-]+$')
        email = self.cleaned_data['email']
        email_exist = models.UserInfo.objects.filter(email=email).exists()

        if not re.match(pattern, email):
            raise ValidationError('邮箱格式不正确')
            # self.add_error('email', '邮箱格式不正确')
        else:
            if email_exist:
                raise ValidationError('邮箱已经注册')
                # self.add_error('email', '邮箱已经注册')
            else:
                return email

    def clean(self):
        if self.cleaned_data.get('password') == self.cleaned_data.get('re_password'):
            # if it's same, return all data
            return self.cleaned_data
        else:
            # default this error was added to errors, not field'r errors
            self.add_error('re_password', '两次密码不一致')


class Login_form(forms.Form):
    username = forms.CharField(required=True, max_length=16, error_messages={'required': '用户名不能为空'},
                               widget=forms.TextInput(attrs={'placeholder': '请输入用户名'}))
    password = forms.CharField(required=True, max_length=32, error_messages={'required': '密码不能为空'},
                               widget=forms.PasswordInput(attrs={'placeholder': '请输入密码'}))

    def clean_username(self):
        username = self.cleaned_data.get('username')
        username_exists = models.UserInfo.objects.filter(username=username).exists()
        if not username_exists:
            raise ValidationError('用户名不存在')
            # self.add_error('username', '用户名不存在')
        else:
            return username

    def clean_password(self):
        password = self.cleaned_data.get('password')
        if len(password) < 8:
            raise ValidationError('密码不正确')
            # self.add_error('password', '密码不正确')
        else:
            return password


class CustomerModelForm(forms.ModelForm):
    class Meta:
        model = models.Customer
        fields = '__all__'

        widgets = {
            'birthday': forms.TextInput(attrs={'type': 'date'}),
        }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for field_name, field in self.fields.items():
            if not isinstance(field, MultiSelectFormField):
                field.widget.attrs.update({'class': 'form-control'})


class ConsultRecordModelForm(forms.ModelForm):
    class Meta:
        model = models.ConsultRecord
        fields = '__all__'
        exclude = ['delete_status', ]

    def __init__(self, request, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for field_name, field in self.fields.items():
            if field_name == 'consultant':
                # only the login user
                field.queryset = models.UserInfo.objects.filter(username=request.session.get('username'))

            if field_name == 'customer':
                # only the consultant's customer
                field.queryset = models.Customer.objects.filter(consultant__username=request.session.get('username'))

            field.widget.attrs.update({'class': 'form-control'})


class EnrollmentModelForm(forms.ModelForm):
    class Meta:
        model = models.Enrollment
        fields = '__all__'
        exclude = ['delete_status', ]

    def __init__(self, *args, **kwargs):
        super(EnrollmentModelForm, self).__init__(*args, **kwargs)
        for field_name, field in self.fields.items():
            field.widget.attrs.update({'class': 'form-control'})


class CourseRecordModelForm(forms.ModelForm):
    class Meta:
        model = models.CourseRecord
        fields = '__all__'

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for field_name, field in self.fields.items():
            field.widget.attrs.update({'class': 'form-control'})


class StudyRecordModelForm(forms.ModelForm):
    class Meta:
        model = models.StudyRecord
        fields = '__all__'

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for field_name, field in self.fields.items():
            field.widget.attrs.update({'class': 'form-control'})
